
import SwiftUI
import GRDB

struct AddressBookView: View {
    @State var persons = [Row]()
    @State var values = [Row]()
    @State var valueEntries = [Row]()
    @State var loaded = false

    var body: some View {
        List {
            if loaded {
                ForEach(persons) { row in
                    HStack {
                        let array: [String] = [row["First"], row["Last"], row["Organization"]].compactMap({$0})
                        NavigationLink(array.joined(separator: " "), destination: AddressBookContactView(row: row, values: values, valueEntries: valueEntries))
                    }
                }
            }
        }.onAppear(perform: {
            do {
                let dbPool = try DatabasePool(path: addressBookPath)
                persons = try dbPool.read { db in
                    return try Row.fetchAll(db, sql: "SELECT * FROM ABPerson")
                }
                values = try dbPool.read { db in
                    return try Row.fetchAll(db, sql: "SELECT * FROM ABMultiValue")
                }
                valueEntries = try dbPool.read { db in
                    return try Row.fetchAll(db, sql: "SELECT * FROM ABMultiValueEntry")
                }
            } catch {
                print(error)
            }
            loaded = true
        })
    }
}

struct AddressBookView_Previews: PreviewProvider {
    static var previews: some View {
        AddressBookView()
    }
}
